package com.rongke.sms;

import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.UUID;

import jodd.util.StringUtil;

/**
 * 玄武短信下发
 * 
 * @author Administrator
 *
 */
public class SmsGMUtils {

	private static final Logger LOGGER = Logger.getLogger(SmsGMUtils.class);

	private static final String DEFAULT_SMS_GW_IP = "211.147.239.62";
	private static final int DEFAULT_SMS_GW_PORT = 9050;
	private static final String DEFAULT_SMS_GW_URL = "/cgi-bin/sendsms?";

	private static final String DEFAULT_SMS_GW_USERNAME = "zsxd@zsxd";
	private static final String DEFAULT_SMS_GW_PSWD_MD5 = "78ae8840a2959ac7e43e9fc93eb67965";

	private static final int DEFAULT_CONN_TIMEOUT = 3000;
	private static final int DEFAULT_READ_TIMEOUT = 3000;

	private static HashMap<String, String> codeMap = new HashMap<>();

	/**
	 * 发送验证码
	 * 
	 * @param phone
	 *            电话号码
	 * @return
	 * @throws Exception
	 */
	public static boolean sendSms(String phone, String content) {
		LOGGER.info("Send sms, phone=" + phone + ",content=" + content);

		if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(content)) {
			LOGGER.error("get null param, skip sms");
			return false;
		}

		HttpURLConnection conn = null;
		OutputStream out = null;
		try {
			/**
			 * HTTP-GET请求参数：发送短信 密码可明文，可密文：version为空，密码明文传输，为1.0，密码MD5加密传输
			 * 短信内容，可GBK，UTF8传输：encode为空或0,内容gbk编码传输；encode为1，内容以utf-8编码传输
			 * msgtype=1为短短信，4为长短信，长短信包含短短信 需要匹配状态报告，提交时必须要batchid
			 */
			String encodeContent = URLEncoder.encode(content, "utf-8");
			String version = "1.0";
			int encode = 1;
			UUID batchid = UUID.randomUUID();
			int msgtype = 1;

			StringBuilder sb = new StringBuilder(DEFAULT_SMS_GW_URL);
			sb.append("username=").append(DEFAULT_SMS_GW_USERNAME);
			sb.append("&password=").append(DEFAULT_SMS_GW_PSWD_MD5);
			sb.append("&to=").append(phone);
			sb.append("&text=").append(encodeContent);
			sb.append("&msgtype=").append(msgtype);
			sb.append("&version=").append(version);
			sb.append("&encode=").append(encode);
			sb.append("&batchid=").append(batchid);

			URL url = new URL("http", DEFAULT_SMS_GW_IP, DEFAULT_SMS_GW_PORT,
					sb.toString());
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setConnectTimeout(DEFAULT_CONN_TIMEOUT);
			conn.setReadTimeout(DEFAULT_READ_TIMEOUT);

			// 开始传输
			String rsp = convertStreamToString(conn.getInputStream());
			return "0".equals(rsp);
		} catch (Exception e) {
			LOGGER.error("send sms failed", e);
			return false;
		} finally {
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					LOGGER.error("close io failed", e);
				}
			}

			if (null != conn) {
				conn.disconnect();
			}
		}
	}

	private static String convertStreamToString(InputStream in) {
		try {
			if (null == in) {
				return null;
			}

			Writer writer = new StringWriter();
			char[] buffer = new char[1024];
			Reader reader = new BufferedReader(new InputStreamReader(in));
			int n;
			while ((n = reader.read(buffer)) != -1) {
				writer.write(buffer, 0, n);
			}
			return writer.toString();
		} catch (Exception e) {
			return null;
		} finally {
			try {
				in.close();
			} catch (IOException e) {
			}
		}
	}

	/**
	 * 校验验证码
	 * 
	 * @param phone
	 *            手机号码
	 * @param code
	 *            验证码
	 * @return true表示成功，false表示失败
	 * @throws Exception
	 */
	public static Boolean checkCode(String phone, String code) throws Exception {
		System.out.println(codeMap);
		String resultCode = codeMap.get(phone);
		if (resultCode == null || resultCode.equals("")
				|| !resultCode.equals(code)) {
			return false;
		} else {
			codeMap.remove(phone);
			return true;
		}

	}

	// /**
	// * 发送模板
	// *
	// * @param phone
	// * 电话号码
	// * @return
	// * @throws Exception
	// */
	// public static Boolean sendTemplet(String phone, SmsTempletEnum stEnum)
	// throws Exception {
	// DefaultHttpClient httpClient = new DefaultHttpClient();
	// // 6位随机数
	// String code = RandomUtils.randomString(6);
	//
	// // 创建StringBuffer对象用来操作字符串
	// StringBuilder sb = new StringBuilder(URL);
	// sb.append("?name=").append(NAME);
	// sb.append("&pwd=").append(PWD);
	// sb.append("&dst=").append(phone);
	// sb.append("&msg=").append(
	// URLEncoder.encode(stEnum.getTypeName(), "GB2312"));
	// System.out.println(sb.toString());
	// HttpPost httpPost = new HttpPost(sb.toString());
	// HttpResponse response = httpClient.execute(httpPost);
	//
	// // 执行结果
	// String result = EntityUtils.toString(response.getEntity());
	// if (result.contains("num=0")) {
	// return false;
	// } else {
	// codeMap.put(phone, code);
	// return true;
	// }
	// }

	// public static void main(String args[]) throws Exception {
	// /*
	// * sendCode("18757550469"); Boolean aBoolean = checkCode("18757550469",
	// * "123456"); System.out.println(aBoolean); System.out.println(codeMap);
	// */
	//
	// sendSms("18651609585", "测试12345");
	// }
}
